<script lang="ts" setup>
import { onMounted, ref } from 'vue';

const props = defineProps({
  speed: {
    type: Number,
    default: 50,
  },
  reverse: {
    type: Boolean,
    default: false,
  },
});

const contentNumber = ref(1);
const elements = ref<HTMLDivElement[]>([]);
const elementNumber = ref(1);

const emit = defineEmits(['changeHeight']);

onMounted(() => {
  contentNumber.value = 2;
  elementNumber.value = elements.value?.[0]?.children?.length ?? 1;

  // Calculate the marquee height
  const marqueeHeight = elements.value?.[0]?.offsetHeight || 0;

  // Emit the height to the parent component
  emit('changeHeight', marqueeHeight);
});
</script>

<template>
  <div class="marquee">
    <div class="marquee__body transform-gpu" :class="{ 'marquee--reverse': props.reverse, 'marquee--start': contentNumber > 1 }" :style="{ '--marquee-speed': `${props.speed * elementNumber}s` }">
      <div class="marquee__content" v-for="n in contentNumber" :key="n" ref="elements">
        <slot></slot>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.marquee {
  display: flex;
  flex-direction: column; /* 设置为垂直方向 */
  overflow: hidden;

  .marquee__body {
    position: relative;

    .marquee__content {
      display: flex;
      flex-direction: column; /* 设置内容为垂直方向 */
      width: 100%;
      animation-duration: var(--marquee-speed);
      animation-timing-function: linear;
      animation-iteration-count: infinite;
      animation-fill-mode: both;
      will-change: transform;

      &:nth-child(2) {
        position: absolute;
        top: 0;
        left: 0;
        display: none;
      }
    }

    &.marquee--start {
      .marquee__content {
        &:nth-child(1) {
          animation-name: marquee-first;
        }

        &:nth-child(2) {
          display: flex;
          animation-name: marquee-second;
        }
      }
    }

    /* Reverse animation */
    &.marquee--reverse {
      &.marquee--start {
        .marquee__content {
          &:nth-child(1) {
            animation-name: marquee-first-reverse;
          }

          &:nth-child(2) {
            display: flex;
            animation-name: marquee-second-reverse;
          }
        }
      }
    }

    /* Pause on hover */
    &:hover {
      .marquee__content {
        animation-play-state: paused;
      }
    }

    @keyframes marquee-first {
      from {
        transform: translateY(0%);
      }

      to {
        transform: translateY(-100%);
      }
    }

    @keyframes marquee-second {
      from {
        transform: translateY(100%);
      }

      to {
        transform: translateY(0%);
      }
    }

    @keyframes marquee-first-reverse {
      from {
        transform: translateY(0%);
      }

      to {
        transform: translateY(100%);
      }
    }

    @keyframes marquee-second-reverse {
      from {
        transform: translateY(-100%);
      }

      to {
        transform: translateY(0%);
      }
    }
  }
}
</style>
